package com.gxa.javaserver.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.javaserver.pojo.Device;
import com.gxa.javaserver.pojo.PyData;
import com.gxa.javaserver.pojo.ScanData;
import com.gxa.javaserver.pojo.TypeConst;
import com.gxa.javaserver.service.DeviceService;
import com.gxa.javaserver.service.ScanDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;

/**
 * 用来解析传递的数据
 * @author:Teacher黄
 * @date:Created at 2020/06/17
 */
@Service
public class ProcessDataService {

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private ScanDataService scanDataService;


    /**
     * 解析并处理数据
     * @param data
     */
    public void process(String data) throws JsonProcessingException {

        // 解析data转换成Java的PyData
        PyData pyData = getPyData(data);
        // 判断类型
        if(TypeConst.REGISTER.equals(pyData.getTypeCode())){
            // 将注册信息入库
            String deviceData = pyData.getData();
            // 将deviceData转换成 Device对象
            // 将单引号替换成双引号
            deviceData = deviceData.replaceAll("'","\"");
            Device device = (Device) getEntityData(deviceData, Device.class);
            // 入库
            deviceService.insert(device);
        }else{
            // 其余的数据都进入scan_data数据表中
            // 构造一个scanData
            ScanData scanData = new ScanData(pyData.getBoardId(), pyData.getTypeCode(), pyData.getData(), new Timestamp(System.currentTimeMillis()));
            scanDataService.insert(scanData);
        }

    }


    /**
     * 解析传递数据的方法
     * @param data
     * @return
     * @throws JsonProcessingException
     */
    private PyData getPyData(String data) throws JsonProcessingException {
        // 利用jackson进行数据的解析
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(data, PyData.class);
    }

    /**
     * 获取对应实体的对象
     * @param data
     * @param clazz
     * @return
     * @throws JsonProcessingException
     */
    public Object getEntityData(String data, Class clazz) throws JsonProcessingException {
        // 利用jackson进行数据的解析
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(data, clazz);
    }









}
